<template>
  <div class="login">
    <img class="login-content-bg" src="../assets/images/login-bg2.png" />
    <img class="login-content-bg2" src="../assets/images/login-bg2-img.png" />

    <div class="login-box">
      <div class="left">
        <div class="top">
          <span class="title">{{ loginTitle }} </span>
          <span class="banben">{{ loginBanben }} </span>
        </div>

        <div class="notice" v-if="noticeBody">
          <span class="tz">通知：</span>
          <br />
          <el-skeleton :rows="6" animated v-if="!noticeBody" />
          <p class="nr" v-html="noticeBody" v-else></p>
        </div>

        <div class="liulanqi">
          兼容常见的 PC 浏览器：
          <br />
          <span>
            <!-- Chrome，Firefox，Edge，QQ 浏览器-极速模式，/ -->
            <a download="Google Chrome" href="/homepage/chrome/chrome.zip"
              >Chrome</a
            >，
            <a download="Firefox Chrome" href="/homepage/chrome/firefox.zip"
              >Firefox</a
            >，
            <a download="Edge" href="/homepage/chrome/edge109.zip">Edge</a>，
            <a download="QQ Chrome" href="/homepage/chrome/qq.zip"
              >QQ浏览器-极速模式</a
            >，
            <a download="360 Chrome" href="/homepage/chrome/360.zip"
              >360 浏览器-极速模式</a
            >
          </span>
        </div>
        <div class="copyright">
          Copyright © 2003-2023 国网山西省电力公司 山西鸿顺通科技有限公司<br />
          版权所有 国网安备051156804号
        </div>
      </div>
      <el-form
        ref="loginForm"
        :model="loginForm"
        :rules="loginRules"
        class="login-form"
        size="medium"
      >
        <!-- <h3 class="title">网域网站内容管理系统</h3> -->
        <!-- <h2 class="title" :style="captchaOnOff?'margin-top:40px':''">网域网站内容管理系统</h2> -->
        <!-- <h2 class="title" :style="captchaOnOff?'margin-top:40px':''">2022年国家级教学成果奖<br>信息发布平台</h2> -->

        <h2 class="title">后台管理</h2>
        <el-form-item prop="username">
          <el-input
            v-model="loginForm.username"
            type="text"
            auto-complete="off"
            placeholder="账号"
            @keyup.enter.native="handleLogin"
          >
            <svg-icon
              slot="prefix"
              icon-class="user"
              class="el-input__icon input-icon"
            />
          </el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            v-model="loginForm.password"
            type="password"
            auto-complete="off"
            placeholder="密码"
            show-password
            @keyup.enter.native="handleLogin"
          >
            <svg-icon
              slot="prefix"
              icon-class="password"
              class="el-input__icon input-icon"
            />
          </el-input>
        </el-form-item>
        <el-form-item prop="code" v-if="captchaOnOff">
          <el-input
            v-model="loginForm.code"
            auto-complete="off"
            placeholder="验证码"
            style="width: 70%"
            @keyup.enter.native="handleLogin"
          >
            <svg-icon
              slot="prefix"
              icon-class="validCode"
              class="el-input__icon input-icon"
            />
          </el-input>
          <div class="login-code">
            <img :src="codeUrl" @click="getCode" class="login-code-img" />
          </div>
        </el-form-item>
        <el-checkbox
          v-model="loginForm.rememberMe"
          style="margin: 0px 0px 25px 0px"
          >记住密码</el-checkbox
        >
        <p
          style="color: red; float: right; padding: 0; margin: 0"
          v-if="smsFlag"
        >
          连续登录失败超出5次,账号将被锁定。
        </p>
        <el-form-item style="width: 100%">
          <el-button
            :loading="loading"
            size="medium"
            type="primary"
            style="
              width: 100%;
              height: 50px;
              border-radius: 25px;
              background: #3fad98;
            "
            @click.native.prevent="handleLogin"
          >
            <span v-if="!loading">登 录</span>
            <span v-else>登 录 中...</span>
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-dialog
      v-dialogDrag
      :title="title"
      :visible.sync="open"
      width="400px"
      append-to-body
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      style="margin-top: 30vh"
    >
      <el-form :model="ticketForm" label-width="60px" :rules="rules">
        <el-form-item label="问题" prop="dictLabel">
          <el-select
            v-model="ticketForm.dictLabel"
            placeholder="请选择问题"
            style="width: 100%"
          >
            <el-option
              v-for="item in questionList"
              :key="item.dictValue"
              :label="item.dictLabel"
              :value="item.dictValue"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="答案" prop="answer">
          <el-input
            v-model="ticketForm.answer"
            autocomplete="off"
            placeholder="请输入答案"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="reset">取 消</el-button>
        <el-button type="primary" @click="ticketFormSubmit">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog
      v-dialogDrag
      ref="dialog"
      width="40%"
      title="初始密码修改"
      :show-close="false"
      :visible="dialogFirstLoginVisible"
      custom-class="center-dialog"
    >
      <el-steps :active="active">
        <el-step title="初次登录" />
        <el-step title="修改初始密码" />
        <el-step title="完成" />
      </el-steps>
      <div v-if="active == 1" class="topTip">
        您好，为了您的账号安全，请点击下一步修改初始密码
      </div>
      <div
        v-if="active != 3"
        style="width: 80%; margin: 10px auto 20px; text-align: center"
      >
        <el-form
          ref="firstLoginFormRef"
          :model="firstLoginForm"
          :rules="firstLoginRules"
          label-width="120px"
        >
          <el-row v-show="active == 1">
            <el-col :span="24">
              <el-form-item label="用户名：">
                <el-input
                  v-model="loginId"
                  :disabled="false"
                  readonly
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row v-if="active == 2">
            <el-col :span="24">
              <el-form-item label="旧密码" prop="oldPassword">
                <el-input
                  v-model="firstLoginForm.oldPassword"
                  placeholder="请输入旧密码"
                  maxlength="50"
                  type="password"
                  show-password
                />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="新密码" prop="newPassword">
                <el-popover
                  ref="popover"
                  placement="right"
                  width="300"
                  trigger="focus"
                >
                  <span>
                    必须使用字母、数字和特殊字符组成强口令，<br />长度不小于6个字符，不超过15个字符，注意不要使用空格。
                  </span>
                  <el-input
                    slot="reference"
                    v-model="firstLoginForm.newPassword"
                    placeholder="请输入密码"
                    maxlength="50"
                    type="password"
                    show-password
                  />
                </el-popover>
              </el-form-item>
            </el-col>

            <el-col :span="24">
              <el-form-item label="确认新密码" prop="confirmPassword">
                <el-input
                  v-model="firstLoginForm.confirmPassword"
                  placeholder="请输入密码"
                  maxlength="50"
                  type="password"
                  show-password
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div v-if="active != 1" slot="footer" class="dialog-footer">
          <el-button @click="preTip">上一步</el-button>
          <el-button
            type="primary"
            @click="submitFirstLoginForm('firstLoginFormRef')"
            >下一步</el-button
          >
        </div>
        <div v-else slot="footer" class="dialog-footer">
          <el-button type="primary" @click="nextTip">下一步</el-button>
        </div>
      </div>
      <div v-if="active === 3" class="ImgTip">
        <div style="margin: 20px 0">
          <svg-icon
            v-if="isSuccess === true"
            icon-class="pwdSuccess"
            style="font-size: 40px"
          />
          <svg-icon v-else icon-class="pwdFail" style="font-size: 40px" />
        </div>
        <p v-if="isSuccess === true">修改密码成功</p>
        <p v-else>系统开小差了，导致密码修改失败，请重新修改</p>
        <el-button
          v-if="isSuccess === true"
          type="primary"
          @click="returnDialogTableVisible"
          >重新登录</el-button
        >
        <el-button v-else type="primary" @click="again">重新修改</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getCodeImg,
  getSecurityQuestionList, // 05、读取安全问题列表
  verificationSecurityQuestionList, // 验证安全问题
  getLoginNotice, // 获取通知内容
} from "@/api/login";
import Cookies from "js-cookie";
import { encrypt, decrypt } from "@/utils/jsencrypt";
import { getToken } from "@/utils/auth";

export default {
  name: "Login",
  inject: ["tour"],
  data() {
    const validatePassword = (rule, value, callback) => {
      let mode = 0;
      if (!value) {
        callback(new Error("密码不能为空"));
      } else if (value.length < 6 || value.length > 15) {
        callback(new Error("长度为6-15个字符"));
      } else {
        if (/\d/.test(value)) mode++; //数字
        if (/[A-Z]/.test(value)) mode++; //大写字母
        if (/[a-z]/.test(value)) mode++; //小写字母
        if (/[\W_]/.test(value)) mode++; //特殊字符

        if (mode < 3) {
          callback(new Error("必须包含大写字母、小写字母、数字、符号3种"));
        }
        callback();
      }
    };
    const validatecheckPassword = (rule, value, callback) => {
      if (!value) {
        callback(new Error("确认密码不能为空"));
      } else if (value != this.pwdOverTimeForm.newPassword) {
        callback(new Error("两次输入的密码必须一致!"));
      } else {
        callback();
      }
    };
    const validatecheckPassword2 = (rule, value, callback) => {
      if (!value) {
        callback(new Error("确认密码不能为空"));
      } else if (value != this.firstLoginForm.newPassword) {
        callback(new Error("两次输入的密码必须一致!"));
      } else {
        callback();
      }
    };
    return {
      dialogFirstLoginVisible: false,
      smsFlag: false,
      active: 1,
      codeUrl: "",
      cookiePassword: "",
      loginForm: {
        username: process.env.NODE_ENV === "development" ? "dsnwwz" : "",
        password: process.env.NODE_ENV === "development" ? "Gyx,05896." : "",
        rememberMe: false,
        code: "",
        uuid: "",
      },
      ticketForm: {
        ticket: "",
      },
      open: false,
      title: "",
      loginRules: {
        username: [
          { required: true, trigger: "blur", message: "用户名不能为空" },
        ],
        password: [
          { required: true, trigger: "blur", message: "密码不能为空" },
        ],
        code: [
          { required: true, trigger: "change", message: "验证码不能为空" },
        ],
      },
      rules: {
        dictLabel: [
          { required: true, trigger: "blur", message: "问题不能为空" },
        ],
        answer: [{ required: true, trigger: "blur", message: "答案不能为空" }],
      },
      // 第一次登录改密码
      firstLoginForm: {
        oldPassword: "",
        newPassword: "",
        confirmPassword: "",
      },
      // 表单校验
      firstLoginRules: {
        oldPassword: [
          { required: true, message: "请输入旧密码", trigger: "blur" },
        ],
        newPassword: [
          { required: true, validator: validatePassword, trigger: "blur" },
        ],
        confirmPassword: [
          {
            required: true,
            validator: validatecheckPassword2,
            trigger: "blur",
          },
        ],
      },
      loading: false,
      captchaOnOff: true,
      redirect: undefined,
      questionList: [],

      loginTitle:
        city_name == "dwdt" ? "山西电网动态系统" : process.env.VUE_APP_TITLE,
      loginBanben: city_name == "dwdt" ? "v2.1" : process.env.VUE_APP_BANBEN,

      noticeBody: "",
    };
  },
  computed: {
    loginId() {
      return this.$store.state.user.loginId;
    },
  },
  watch: {
    $route: {
      handler: function (route) {
        this.redirect = route.query && route.query.redirect;
      },
      immediate: true,
    },
  },
  created() {
    this.getNotice();
    this.getCode();
    this.getCookie();
    this.getList();
  },
  methods: {
    nextTip() {
      this.active += 1;
    },
    preTip() {
      this.active -= 1;
    },
    getList() {
      getSecurityQuestionList().then((res) => {
        this.questionList = res.data;
      });
    },
    getCode() {
      if (getToken()) {
        this.$store.dispatch("LogOut").then(() => {});
      }
      getCodeImg().then((res) => {
        this.captchaOnOff =
          res.captchaOnOff === undefined ? true : res.captchaOnOff;
        if (this.captchaOnOff) {
          this.codeUrl = "data:image/gif;base64," + res.img;
          this.loginForm.uuid = res.uuid;
        }
      });
    },
    getCookie() {
      const username = Cookies.get("username");
      const password = Cookies.get("password");
      const rememberMe = Cookies.get("rememberMe");
      this.loginForm = {
        username: username === undefined ? this.loginForm.username : username,
        password:
          password === undefined ? this.loginForm.password : decrypt(password),
        rememberMe: rememberMe === undefined ? false : Boolean(rememberMe),
      };
    },
    handleLogin() {
      this.$refs.loginForm.validate((valid) => {
        if (valid) {
          this.smsFlag = false;
          this.loading = true;
          console.log("getToken(): ", getToken());
          if (getToken()) {
            this.$confirm("已有用户登录成功, 是否继续登录?", "提示", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning",
            })
              .then(() => {
                console.log("退出");
                this.$store.dispatch("LogOut").then(() => {
                  this.login();
                });
              })
              .catch(() => {
                this.$router
                  .push({ path: this.redirect || "/" })
                  .catch(() => {});
              });
          } else {
            this.login();
          }
        }
      });
    },
    login() {
      if (this.loginForm.rememberMe) {
        Cookies.set("username", this.loginForm.username, { expires: 30 });
        Cookies.set("password", encrypt(this.loginForm.password), {
          expires: 30,
        });
        Cookies.set("rememberMe", this.loginForm.rememberMe, {
          expires: 30,
        });
      } else {
        Cookies.remove("username");
        Cookies.remove("password");
        Cookies.remove("rememberMe");
      }
      this.$store
        .dispatch("Login", this.loginForm)
        .then((res) => {
          if (res.code == 203) {
            this.open = true;
            this.title = "双因子验证";
            this.ticketForm.ticket = res.ticket;
            return;

            this.$prompt("请输入邮箱", "双因子验证", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
            })
              .then(({ value }) => {
                this.$message({
                  type: "success",
                  message: "你的邮箱是: " + value,
                });
              })
              .catch(() => {
                this.$message({
                  type: "info",
                  message: "取消输入",
                });
              });
            return;
          }
          this.$router.push({ path: this.redirect || "/" }).catch(() => {});
        })
        // .then(()=>{
        //   this.$nextTick(()=>{
        //     setTimeout(() => {
        //   this.tour.$refs.tour.init()
        //     }, 1000);
        //   })
        // })
        .catch(() => {
          this.smsFlag = true;
          this.loading = false;
          if (this.captchaOnOff) {
            this.getCode();
          }
        });
    },
    submitFirstLoginForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          updateUserPwd(
            this.firstLoginForm.oldPassword,
            this.firstLoginForm.newPassword
          )
            .then((res) => {
              this.nextTip();
              if (res.code == 200) {
                this.isSuccess = true;
              } else {
                this.isSuccess = false;
              }
            })
            .then(() => {});
        }
      });
    },
    /**
     * 双因子认证登录
     */
    ticketFormSubmit() {
      // this.ticketForm.ticket = this.ticket;
      this.$store
        .dispatch("TwoLogin", this.ticketForm)
        .then((res) => {
          this.$router.push({ path: this.redirect || "/" }).catch(() => {});
        })
        .catch(() => {
          this.smsFlag = true;
          this.loading = false;
          if (this.captchaOnOff) {
            this.getCode();
          }
        });
      // verificationSecurityQuestionList(this.ticketForm).then((res) => {
      // });
    },
    reset() {
      this.ticketForm = {};
      this.$message({
        type: "info",
        message: "取消登录",
      });
    },

    /**
     * 获取登录界面通知内容
     * @param {channelId} 在系统参数里面设置
     */
    getNotice() {
      getLoginNotice().then((res) => {
        this.noticeBody = res.data?.body || undefined;
      });
    },
  },
};
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
$main-color: "#2468f2";
.login {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  // background-size: contain;
  // background-repeat: no-repeat;
  // background-image: url('../assets/images/bg2.png');
}
.login-content-bg {
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 100vh;
  object-fit: cover;
  z-index: -1;
  mix-blend-mode: hard-light;
}
.login-content-bg2 {
  position: absolute;
  right: 0;
  top: 0;
  width: 100%;
  height: 100vh;
  object-fit: cover;
  z-index: -1;
  mix-blend-mode: hard-light;
}

.login-box {
  // height: 508px;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  // background: url('../assets/images/login-bg.png') no-repeat 0 50% #f5f7ff;
  background-size: 50%;
  border-radius: 12px;
  display: flex;
  flex-direction: row;
  .left {
    flex: 1;
    min-width: 528px;
    margin-right: 84px;
    display: flex;
    flex-direction: column;
    justify-content: space-around;
    align-content: flex-start;
    .top {
      padding-top: 10px;
      text-align: left;
      .title {
        font-family: PingFangSC-Medium;
        font-size: 36px;
        font-weight: normal;
        letter-spacing: 0em;
        font-weight: 700;
        color: #2e3241;
      }
      .banben {
        font-family: PingFangSC-Medium;
        font-size: 18px;
        font-weight: normal;
        letter-spacing: 0em;
        margin-left: 17px;
        color: #627075;
      }
    }
    .notice {
      font-family: PingFangSC-Regular;
      font-size: 18px;
      font-weight: normal;
      line-height: 18px;
      letter-spacing: 0em;
      padding: 10px 0;
      border-bottom: 1px solid #e8e8e8;
      max-height: 267px;
      min-height: 267px;
      .tz {
        font-weight: 700;
        font-size: 20px;
        line-height: 38px;
      }
      .nr {
        line-height: 26px;
        text-indent: 2em;
        margin: 0;
        padding: 0;
        display: -webkit-box;
        -webkit-box-orient: vertical;
        -webkit-line-clamp: 8;
        overflow: hidden;
        ::v-deep p {
          margin: 0;
          padding: 0;
          font-size: 16px;
        }
      }
    }
    .liulanqi {
      border-radius: 8px;
      background: linear-gradient(190deg, #6acdbc 0%, #41ad99 100%);
      padding: 27px 0 0 32px;
      font-size: 16px;
      font-weight: normal;
      line-height: 28px;
      letter-spacing: 0em;
      color: #ffffff;
      width: 528px;
      height: 98px;
      box-sizing: border-box;
      span {
        font-size: 14px;
      }
    }
    .copyright {
      font-family: PingFangSC-Medium;
      font-size: 14px;
      font-weight: normal;
      line-height: 24px;
      letter-spacing: 0em;
      text-align: center;
      color: #7e828c;
      padding: 5px 0;
    }
  }
  .login-form {
    height: 100%;
    padding: 40px 68px;
    border-radius: 10px;
    background: #ffffff;
    width: 528px;
    box-shadow: 0px 4px 10px 0px rgba(0, 0, 0, 0.3);
    .title {
      // margin: 60px auto 44px;
      margin: 0;
      padding: 0 12px;
      font-weight: bold;
      color: #2c3645;
      text-align: left;
      height: 40px;
      line-height: 40px;
      font-size: 22px;
      border-bottom: 1px solid #f0f0f0;
      position: relative;
      margin-bottom: 40px;
      &:after {
        position: absolute;
        left: 0;
        bottom: 0;
        width: 116px;
        content: "";
        height: 3px;
        background: $main-color;
      }
    }
  }
}

.login-tip {
  font-size: 13px;
  text-align: center;
  color: #bfbfbf;
}
.login-code {
  // width: 33%;
  height: 38px;
  float: right;
  img {
    cursor: pointer;
    vertical-align: middle;
  }
}

.login-code-img {
  height: 38px;
}
::v-deep .el-form-item {
  margin-bottom: 30px;
  .el-form-item__content {
    line-height: 42px;
    .el-input {
      height: 42px;
      .el-input__inner {
        height: 42px;
        line-height: 42px;
      }
    }
    .input-icon {
      height: 42px;
      width: 14px;
      margin-left: 2px;
    }
  }
}
</style>
<style scoped lang="scss">
/* @media screen and (max-width: 1200px) {.login-box{
    height: 50%;

  }

  ::v-deep .el-form-item {
    margin-bottom: 10px;
  }
} */
@media screen and (max-height: 800px) {
  .login-box {
    /* max-height: 50%; */
  }
  .login-form {
    padding: 10px;
  }

  .liulanqi {
    bottom: 20px;
  }
  ::v-deep .el-form-item {
    margin-bottom: 15px;
  }
}
@media screen and (max-width: 1200px) {
  .login-box .left {
    margin: 0;
  }
}
@media screen and (max-width: 1100px) {
  .login-box {
    flex-direction: column-reverse;
    .left {
      .top,
      .notice {
        display: none;
      }
      .liulanqi,
      .copyright {
        position: absolute;
      }
      .liulanqi {
        bottom: -120px;
      }
      .copyright {
        bottom: -190px;
        color: #000;
      }
    }
  }
}
@media screen and (max-width: 992px) {
  .login-box {
    width: auto;
  }
  .login-form {
    float: unset;
    padding: 20px;
  }
}
</style>
